package com.example.poemtest.index.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.poemtest.Activity.BottomNavigationViewActivity;
import com.example.poemtest.R;
import com.example.poemtest.databinding.ActivityFlyFlowerOrderBinding;
import com.example.poemtest.databinding.DialogChooseTextBinding;
import com.example.poemtest.entity.PoetryInfoBean;
import com.example.poemtest.index.adapter.FlyFlowerOrderAdapter;
import com.example.poemtest.index.dialog.DialogChooseText;
import com.example.poemtest.index.entity.ProtryBean;
import com.example.poemtest.index.util.GetJsonDataUtil;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;
import com.google.gson.Gson;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 飞花令的页面
 */
public class FlyFlowerOrderActivity extends AppCompatActivity {

    private final static String TAG = "诗";

    private ActivityFlyFlowerOrderBinding binding;

    DialogChooseText dialogChooseText;
    DialogChooseText.Builder dialogChooseTextbuilder;
    DialogChooseTextBinding chooseTextBinding;
    private String chooseText;
    private List<PoetryInfoBean.PoetryInfo> allMessageDataList;  //数据库
    private List<PoetryInfoBean.PoetryInfo> queryDataList;  //手机端查询出诗句列表
    private List<PoetryInfoBean.PoetryInfo> haveShowList;  //已用过的诗词列表

    FlyFlowerOrderAdapter mDetailChatAdapter;  //主页adapter
    private List<PoetryInfoBean.PoetryInfo> showDataList;
    private int onPoetryNum = 0;
    private ImageView back;

    public static void start(Context context) {
        Intent starter = new Intent(context, FlyFlowerOrderActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FullScreenUtil.getInstance().fullScreen(this,true);
        //初始化databinding
        binding = DataBindingUtil.setContentView(this, R.layout.activity_fly_flower_order);
        //所有的数据列表
        allMessageDataList = new ArrayList<>();
        queryDataList = new ArrayList<>();
        showDataList = new ArrayList<>();
        haveShowList = new ArrayList<>();
        dialoginit();
        setData();
//        initJsonData();
        back = findViewById(R.id.setup_safe_to_mine);

        mDetailChatAdapter = new FlyFlowerOrderAdapter(this);
        binding.rv.setAdapter(mDetailChatAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(FlyFlowerOrderActivity.this);
        linearLayoutManager.setStackFromEnd(true);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rv.setLayoutManager(linearLayoutManager);
        mDetailChatAdapter.setLists(showDataList);

        binding.ivSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogChooseText.show();
            }
        });

        binding.TvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("诗", "binding.EtMsgContent.getText().toString(): "+binding.EtMsgContent.getText().toString());
                if (TextUtils.isEmpty(chooseText)){
                    binding.EtMsgContent.getText().clear();
                    Toast.makeText(FlyFlowerOrderActivity.this,"请先设置飞花令的关键字",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(binding.EtMsgContent.getText())){
                    Toast.makeText(FlyFlowerOrderActivity.this,"请输入您的诗句",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (binding.EtMsgContent.getText().length()<2){
                    Toast.makeText(FlyFlowerOrderActivity.this,"请输入2个字以上的诗句",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!binding.EtMsgContent.getText().toString().contains(chooseText)){
                    binding.EtMsgContent.getText().clear();
                    Toast.makeText(FlyFlowerOrderActivity.this,"输入的诗句没有“" + chooseText + "”字。",Toast.LENGTH_SHORT).show();
                    return;
                }
                //判断诗句是否正确，且在数据库内
                PoetryInfoBean.PoetryInfo myProtryBean = new PoetryInfoBean.PoetryInfo();
                boolean inputRight = false;
                for (PoetryInfoBean.PoetryInfo poetryInfo : Constant.poetryInfos) {
                    if (StringUtils.contains(poetryInfo.getPoetryContent(),binding.EtMsgContent.getText().toString())){
                        myProtryBean = poetryInfo;
                        inputRight = true;
                    }
                }
                if (inputRight){
                    //判断是否使用过了
                    boolean haveUserd = false;
                    for (PoetryInfoBean.PoetryInfo poetryInfo : haveShowList) {
                        if (StringUtils.contains(poetryInfo.getPoetryContent(),binding.EtMsgContent.getText().toString())){
                            haveUserd = true;
                        }
                    }
                    if (haveUserd){
                        Toast.makeText(FlyFlowerOrderActivity.this,"输入的诗句已被使用过",Toast.LENGTH_SHORT).show();
                    }else {
                        haveShowList.add(myProtryBean);
                        myProtryBean.setIsmyself(true);
                        mDetailChatAdapter.addItem(myProtryBean);
                        scrollBottom();

                        binding.EtMsgContent.getText().clear();
                        mhandler.sendEmptyMessageDelayed(0x124,1000);

                        onPoetryNum = onPoetryNum + 1;
                        binding.tvTitle.setText("飞花令："+chooseText + "(" + onPoetryNum + ")");
                    }
                }else {
                    binding.EtMsgContent.getText().clear();
                    Toast.makeText(FlyFlowerOrderActivity.this,"输入的诗句不正确，请重新输入",Toast.LENGTH_SHORT).show();
                }
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FlyFlowerOrderActivity.this, BottomNavigationViewActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }

    /**
     * 设置数据
     */
    private void setData() {
        for (PoetryInfoBean.PoetryInfo poetryInfo : Constant.poetryInfos) {
            allMessageDataList.add(poetryInfo);
        }
    }

    private void dialoginit() {
        dialogChooseTextbuilder = new DialogChooseText.Builder(this);
        dialogChooseText = dialogChooseTextbuilder.create();
        dialogChooseText.setCanceledOnTouchOutside(true);
        chooseTextBinding = dialogChooseTextbuilder.getChooseTextBinding();

        chooseTextBinding.btnRefuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogChooseText.dismiss();
            }
        });

        chooseTextBinding.btnAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(chooseTextBinding.etText.getText())){
                    chooseText = chooseTextBinding.etText.getText().toString();
                    chooseTextBinding.etText.getText().clear();
                    dialogChooseText.dismiss();
                    binding.tvTitle.setText("飞花令："+chooseText);

                    //清空列表
                    mDetailChatAdapter.setShowText(chooseText);
                    showDataList.clear();
                    queryDataList.clear();
                    haveShowList.clear();
                    onPoetryNum = 0;

                    PoetryInfoBean.PoetryInfo poetryInfo = new PoetryInfoBean.PoetryInfo();
                    poetryInfo.setIsmyself(true);
//                    List<String> strList = new ArrayList<>();
                    String strList="我们来玩飞花令吧，今日飞“" + chooseText + "“字。";
                    poetryInfo.setPoetryContent(strList);

                    mDetailChatAdapter.addItem(poetryInfo);
                    scrollBottom();
                    Log.i("刘", "进度: ");
                    mhandler.sendEmptyMessageDelayed(0x123,1000);
                }else {
                    Toast.makeText(FlyFlowerOrderActivity.this,"请输入文字",Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    //滑动到最底部
    public void scrollBottom() {
        if (null != mDetailChatAdapter&&null != binding.rv) {
            binding.rv.scrollToPosition(mDetailChatAdapter.getItemCount());
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x123:
                    //回应诗句
                    for (PoetryInfoBean.PoetryInfo poetryInfo : allMessageDataList) {
//                        Log.e("能不能",poetryInfo.getPoetryContent());
//                        if (poetryInfo.getPoetryContent().contains(chooseText)){
//                            queryDataList.add(poetryInfo);
//                        }
                        if (StringUtils.contains(poetryInfo.getPoetryContent(), chooseText)) {
                            queryDataList.add(poetryInfo);
                        }
                    }

                    if (queryDataList.size()>0){
                        ResponsePretry(queryDataList.get(0));
                        //记录已使用的诗句
                        haveShowList.add(queryDataList.get(0));
                    }else {
                        Toast.makeText(FlyFlowerOrderActivity.this,"无数据",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 0x124:
                    //回应诗句，先判断是否还有诗句
                    if (queryDataList.size()>haveShowList.size()){
                        //获取在queryDataList中，不在haveShowList中的参数列表
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            List<PoetryInfoBean.PoetryInfo> notInList2 = queryDataList.stream()
                                    .filter(element -> !haveShowList.contains(element))
                                    .collect(Collectors.toList());

                            ResponsePretry(notInList2.get(0));
                            haveShowList.add(notInList2.get(0));
                        }
                    }else {
                        Toast.makeText(FlyFlowerOrderActivity.this,"无数据",Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    private void ResponsePretry(PoetryInfoBean.PoetryInfo mProtryBean){
        mDetailChatAdapter.addItem(mProtryBean);
        scrollBottom();
    }

//    private void initJsonData() {//解析数据
//
//        /**
//         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
//         * 关键逻辑在于循环体
//         *
//         * */
//        String JsonData = new GetJsonDataUtil().getJson(FlyFlowerOrderActivity.this, "protry.json");//获取assets目录下的json文件数据
//
//        allMessageDataList = parseData(JsonData);//用Gson 转成实体
//
//        Log.i(TAG, "initJsonData: "+allMessageDataList.size());
//    }

    public ArrayList<ProtryBean> parseData(String result) {//Gson 解析
        ArrayList<ProtryBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProtryBean entity = gson.fromJson(data.optJSONObject(i).toString(), ProtryBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        mhandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

}